package com.elcl.support.versionupdate;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.elcl.andbaselibrary.R;
import com.elcl.network.AppConstant;
import com.elcl.network.NetWorkUtils;
import com.elcl.util.ApkUtils;
import com.elcl.util.FileUtils;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by lichunlin on 17/6/14.
 * 下载包的主service
 */

public class DownloadService extends Service {

    private static final int TIMEOUT = 60 * 1000;// 超时
    private String app_name;//app的名称
    private int app_icon;//app的icon
    private static String down_url;//下载apk的网络地址
    private static String down_file_path_url;//下载file存放的地址
    private boolean isOpenWifiDownload = false;

    private static final int DOWN_OK = 1;
    private static final int DOWN_ERROR = 0;

    private NotificationManager notificationManager;
    private Notification notification;
    private PendingIntent pendingIntent;
    private RemoteViews contentView;
    private DownloadServiceCtrl downloadServiceCtrl;

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        downloadServiceCtrl = new DownloadServiceCtrl(this);

        getIntentData(intent);
        startDownloadByFileCreate();

        return START_STICKY;
    }

    private void getIntentData(Intent intent) {
        if (null != intent){
            app_name = intent.getStringExtra(AppConstant.KEY_APP_NAME);
            down_url = intent.getStringExtra(AppConstant.KEY_DOWN_URL);
            app_icon = intent.getIntExtra(AppConstant.KEY_APP_ICON, 0);
            down_file_path_url = intent.getStringExtra(AppConstant.KEY_FILE_PATH);
            isOpenWifiDownload = intent.getBooleanExtra(AppConstant.KEY_WIFI_OPEN, isOpenWifiDownload);
        }else{
            stopSelf();
        }
    }

    /**
     * 根据file是否创建来进行下载
     * 1、如果已经下载返回
     * 2、
     */
    private boolean isDownLoad;//是否已下载（下载不一定下载完）(跟断点下载有关系，目前服务器不支持，先放一放)
    private boolean isFileAlreadyExist = false;//文件是否存在
    private long fileSize = 0;//下载的文件的大小（未下载完或者下载完，没有安装）

    private void startDownloadByFileCreate() {
        isDownLoad = FileUtils.createApkFile(down_file_path_url, app_name);
        fileSize = FileUtils.fileSize;
        if (FileUtils.isCreateFileSucess == true) {
            if (!isOpenWifiDownload) {//如果没有开启wifi下载，则显示通知栏下载
                createNotification();
            }
            createThread();
        } else {
            Toast.makeText(this, "获取存储地址失败", Toast.LENGTH_SHORT).show();
            stopSelf();
        }
    }

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWN_OK://下载成功
                    if (!isFileAlreadyExist) {//如果不是文件已下载，提示安装，否则的话，不执行（防止回调两次，fileAlready回调一次，downloadSuccess一次）
                        byte downloadType = 0;
                        if (isOpenWifiDownload) {//如果开启wifi下载，下载成功后回调下载成功
                            downloadType = VersionDownLoadListener.DOWNLOAD_SUCCESS_WIFI;
                        } else {//如果不是wifi下载，成功后，跳出点击安装，通知栏修改内容（点击通知栏跳转安装界面）
                            downloadType = VersionDownLoadListener.DOWNLOAD_SUCCESS;
                            Uri uri = Uri.fromFile(FileUtils.updateFile);
                            Intent intent = new Intent(Intent.ACTION_VIEW);
                            intent.setDataAndType(uri, "application/vnd.android.package-archive");
                            pendingIntent = PendingIntent.getActivity(DownloadService.this, 0, intent, 0);

                            notification.flags = Notification.FLAG_AUTO_CANCEL;

                            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                                NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                                Notification.Builder builder = new Notification.Builder(
                                        DownloadService.this);
                                builder.setContentTitle(app_name);
                                builder.setContentText(getString(R.string.down_sucess));
                                builder.setSmallIcon(app_icon);
                                builder.setContentIntent(pendingIntent);

                                Notification notification = null;
                                notification = builder.build();
                                manager.notify(1, notification);
                            }
                            ApkUtils.installApk(DownloadService.this);
                        }
                        if (null != downloadServiceCtrl){
                            downloadServiceCtrl.downloadSuccess(downloadType);
                        }
                        stopSelf();
                    }
                    break;

                case DOWN_ERROR://下载失败
                    if (!isOpenWifiDownload) {
                        notification.flags = Notification.FLAG_AUTO_CANCEL;

                        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
                            NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                            Notification.Builder builder = new Notification.Builder(
                                    DownloadService.this);
                            builder.setContentTitle(app_name);
                            builder.setContentText(getString(R.string.down_fail));
                            builder.setSmallIcon(app_icon);
                            builder.setContentIntent(pendingIntent);

                            Notification notification = null;
                            notification = builder.build();
                            manager.notify(1, notification);
                        }
                        downloadServiceCtrl.downloadFailed();
                    }
                    stopSelf();
                    break;

                default:
                    break;
            }
        }
    };

    /**
     * createThread方法, 开线程下载
     */
    public void createThread() {
        new DownLoadThread().start();
    }


    private class DownLoadThread extends Thread {
        @Override
        public void run() {
            Message message = new Message();
            try {
                boolean isStartDownLoad = false;
                if (NetWorkUtils.isNetworkAvailable(DownloadService.this)) {
                    if (isOpenWifiDownload) {
                        if (NetWorkUtils.isWifi(DownloadService.this)) {
                            isWifiAvaliable = true;
                            isStartDownLoad = true;
                        }
                    } else {
                        isStartDownLoad = true;
                    }

                    if (isStartDownLoad) {
                        long downloadSize = downloadUpdateFile(down_url, FileUtils.updateFile.toString());
                        if (downloadSize > 0) {
                            message.what = DOWN_OK;
                            handler.sendMessage(message);
                        } else {
                            message.what = DOWN_ERROR;
                            handler.sendMessage(message);
                        }
                    } else {
                        stopSelf();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                message.what = DOWN_ERROR;
                handler.sendMessage(message);
            }
        }
    }


    /**
     * 方法描述：createNotification方法
     */
    public void createNotification() {
        notification = new Notification(
                app_icon,//应用的图标
                app_name + getString(R.string.is_downing),
                System.currentTimeMillis());
        notification.flags = Notification.FLAG_ONGOING_EVENT;

        contentView = new RemoteViews(getPackageName(), R.layout.notification_item);
        contentView.setTextViewText(R.id.notificationTitle, app_name + getString(R.string.is_downing));
        contentView.setTextViewText(R.id.notificationPercent, "0%");
        contentView.setProgressBar(R.id.notificationProgress, 100, 0, false);
        contentView.setImageViewResource(R.id.img_app, app_icon);
        notification.contentView = contentView;

        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(R.layout.notification_item, notification);
    }

    //从服务器下载文件，支持断点下载续传
    public long downloadUpdateFile(String down_url, String file) throws Exception {
        long totalSize;// 文件总大小
        long downloadCount = 0;// 已经下载好的大小
        int updateCount = 0;// 已经上传的文件大小

        InputStream inputStream;
        OutputStream outputStream;

        URL url = new URL(down_url);
        HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
        httpURLConnection.setConnectTimeout(TIMEOUT);
        httpURLConnection.setReadTimeout(TIMEOUT);

        //TODO 断点下载，服务器暂不支持，先关闭
//        httpURLConnection.setRequestProperty("Range", "bytes=" + fileSize);//断点续传下载

        totalSize = httpURLConnection.getContentLength();

        //如果下载的文件大小和服务器的大小一致，就认为已经下载完毕
        if (fileSize == totalSize) {
            isFileAlreadyExist = true;
            downloadServiceCtrl.fileAlreadyDownload();
            if (null != notificationManager) {
                notificationManager.cancel(R.layout.notification_item);
            }
            return 1;
        }

        if (httpURLConnection.getResponseCode() == 404) {
            downloadError();
        }

        inputStream = httpURLConnection.getInputStream();
        //downloadCount = fileSize;//TODO 断点下载，服务器暂不支持，先关闭
//        outputStream = new FileOutputStream(file, isDownLoad);//根据是否下载，来决定是否append //TODO 断点下载，服务器暂不支持，先关闭
        outputStream = new FileOutputStream(file, false);//根据是否下载，来决定是否append

        byte buffer[] = new byte[1024];
        int readsize = 0;

        while ((readsize = inputStream.read(buffer)) != -1) {
            if (isOpenWifiDownload) {
                if (!isWifiAvaliable) {
                    return -1;
                }
            }

            if (httpURLConnection.getResponseCode() == 404) {
                downloadError();
            }

            outputStream.write(buffer, 0, readsize);
            downloadCount += readsize;
            updateCount = (int) (downloadCount * 100 / totalSize);
            if (updateCount >= 100) {
                updateCount = 100;
            }

            if (!isOpenWifiDownload) {
                contentView.setTextViewText(R.id.notificationPercent, updateCount + "%");
                contentView.setProgressBar(R.id.notificationProgress, 100, updateCount, false);
                notification.contentView = contentView;
                notificationManager.notify(R.layout.notification_item, notification);
            }
            downloadServiceCtrl.downloadProgress(updateCount);
        }
        if (httpURLConnection != null) {
            httpURLConnection.disconnect();
        }
        inputStream.close();
        outputStream.close();
        return downloadCount;
    }

    //下载失败
    private void downloadError() {
//        Message message = new Message();
//        message.what = DOWN_ERROR;
//        handler.sendMessage(message);

        downloadServiceCtrl.downloadFailed();
        notificationManager.cancel(R.layout.notification_item);
    }

    private boolean isWifiAvaliable = false;

//    public class WifiReceiver extends BroadcastReceiver {
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            if (intent.getAction().equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {//wifi连接上与否
//                NetworkInfo info = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
//                if (info.getState().equals(NetworkInfo.State.DISCONNECTED)) {//wifi断开，回调
//                    isWifiAvaliable = false;
//                    downloadServiceCtrl.isWifiAvailable(false);
//                } else if (info.getState().equals(NetworkInfo.State.CONNECTED)) {//wifi连接，回调
//                    isWifiAvaliable = true;
//                    WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
//                    downloadServiceCtrl.isWifiAvailable(true);
//                }
//
//            }
//        }
//    }

}
